import React, { PureComponent, Fragment } from 'react';
import {
  Form,
  Input,
  Select,
  Modal,
  Button, Steps,
  Row,
  Col, message, Icon, Tooltip,
} from 'antd';
import { channel, financeMode, repayMode } from '../../../common/options';
import { connect } from 'dva';


const FormItem = Form.Item;
const { Step } = Steps;
const { Option } = Select;

@Form.create()
/* eslint react/no-multi-comp:0 */
@connect(({ equityModels, loading }) => ({
  equityModels,
  loading: loading.models.equityModels,
}))
class UpdateForm extends PureComponent {
  constructor(props) {
    super(props);
    const { dispatch, selectedRows } = props;
    dispatch({
      type: 'equityModels/EnterpriseList',
      payload: {
        status: 6,
        pageSize: 99999,
      },
    });
    dispatch({
      type: 'equityModels/role',
      payload: {},
    });
    this.state = {
      formVals: selectedRows,
      currentStep: 0,
    };

    this.formLayout = {
      labelCol: { span: 8 },
      wrapperCol: { span: 16 },
    };
    this.sortformLayout={
      labelCol: { span: 10 },
      wrapperCol: { span: 14 },
    }
  }


  forward = () => {
    const { currentStep } = this.state;
    this.setState({
      currentStep: currentStep + 1,
    });
  };

  handleNext = currentStep => {
    const { form } = this.props;
    const { formVals: oldValue } = this.state;

    form.validateFields((err, fieldsValue) => {
      if (err) return;
      const formVals = { ...oldValue, ...fieldsValue };
      this.setState({
          formVals: formVals,
        }, () => {
          if (currentStep < 1) {
            this.forward();
          } else {
            formVals.amount = Number(formVals.amount);
            formVals.serviceRate = Number(formVals.serviceRate)/100;
            formVals.otherServiceRate = Number(formVals.otherServiceRate)/100;
            formVals.totalDays = Number(formVals.totalDays);
            formVals.totalServiceFee = Number(formVals.totalServiceFee);
            formVals.overdueRate = Number(formVals.overdueRate);
            formVals.period = 1;
            this.handleAdd(formVals);
          }
        },
      );
    });
  };

  handleAdd(formVals) {
    const { dispatch, handleModalVisible, handleFormReset, selectedRows } = this.props;
    console.log(Object.keys(selectedRows));
    if (Object.keys(selectedRows).length > 0) {
      dispatch({
        type: 'equityModels/update',
        payload: {
          ...formVals,
        },
        callback(res) {

          if (res.code === 200) {
            message.success('修改成功');
            handleModalVisible(false);
            handleFormReset();
          } else {
            message.error(res.errMsg);
          }
        },
      });
    } else {
      dispatch({
        type: 'equityModels/adds',
        payload: {
          ...formVals,
        },
        callback(res) {

          if (res.code === 200) {
            handleModalVisible(false);
            handleFormReset();
            message.success('添加成功');
          } else {
            message.error(res.errMsg);
          }
        },
      });
    }
  }

  backward = () => {
    const { currentStep } = this.state;
    this.setState({
      currentStep: currentStep - 1,
    });
  };
  amountNum = (rule, value, callback) => {
    console.log(value);
    if (parseInt(value) !== Number(value) && value) {
      callback('请输入整数!');
    }
    if (Number(value) === 0&& value) {
      callback('请输入大于0的整数!');
    }
    // if (!city.key) {
    //   callback('Please input your city!');
    // }
    callback();
  };


  renderContent = (currentStep, formVals) => {
    const { form, equityModels: { companyList, setRoleList } } = this.props;
    if (currentStep === 1) {
      let type = form.getFieldValue('type');
      let totalDays = form.getFieldValue('totalDays');
      let result = setRoleList.filter((a, i) => {
        return (a.type === type && a.maxDay >= totalDays && a.minDay <= totalDays);
      });
      let rate = result.length > 0 ? result[0].rate : 0;
      formVals.amount = typeof(formVals.amount) === 'string' ? formVals.amount.replace(',', '') : formVals.amount;
      return [
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={12} sm={24}>
            <FormItem key="enterpriseNo" {...this.formLayout} label="企业名称">
              {form.getFieldDecorator('enterpriseNo', {
                rules: [{ required: true, message: '请选择企业名称！' }],
                initialValue: formVals.enterpriseNo,
              })(
                <Select showSearch
                        filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                        placeholder="请选择企业名称" style={{ width: '100%' }}>
                  {
                    companyList.data.map(item => (
                      <Option value={item.enterpriseNo}>{item.enterpriseName}</Option>
                    ))
                  }
                </Select>,
              )}
            </FormItem>
          </Col>
          <Col md={12} sm={24}>
            <FormItem key="target" {...this.formLayout} label="融资方式">
              {form.getFieldDecorator('financeMode', {
                rules: [{ required: true, message: '请选择融资方式！' }],
                initialValue: formVals.financeMode || 2,
              })(
                <Select placeholder="请选择融资方式" style={{ width: '100%' }}>
                  {financeMode.map(item => (
                    <Option value={item.key} disabled={item.disabled}>{item.value}</Option>
                  ))}
                </Select>,
              )}
            </FormItem>
          </Col>

        </Row>,
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={12} sm={24}>
            <FormItem key="financeType" {...this.formLayout} label="融资类型">
              {form.getFieldDecorator('financeType', {
                rules: [{ required: true, message: '请选择融资类型！' }],
                initialValue: formVals.financeType,
              })(
                <Select placeholder="请选择融资类型" style={{ width: '100%' }}>
                  <Option value={1}>直借</Option>
                  <Option value={2}>保理</Option>
                </Select>,
              )}
            </FormItem>
          </Col>
          <Col md={12} sm={24}>
            <FormItem key="amount" {...this.formLayout} label="融资金额(元)">
              {form.getFieldDecorator('amount', {
                rules: [
                  { required: true, message: '请输入融资金额！' },
                  {
                    validator: this.amountNum,
                  },
                ],
                initialValue: formVals.amount,
              })(<Input type={'Number'} placeholder="请输入融资金额" maxLength={7}/>)}
            </FormItem>
          </Col>

        </Row>,
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={12} sm={24}>
            <FormItem key="repayMode" {...this.formLayout} label="还款方式">
              {form.getFieldDecorator('repayMode', {
                rules: [{ required: true, message: '请选择还款方式！' }],
                initialValue: formVals.repayMode || 1,
              })(
                <Select placeholder="请选择还款方式" style={{ width: '100%' }}>
                  {repayMode.map(item => (
                    <Option value={item.key} key={item.key} disabled={item.disabled}>{item.value}</Option>
                  ))}
                </Select>,
              )}
            </FormItem>
          </Col>

          <Col md={12} sm={24}>
            <FormItem key="serviceRole" {...this.formLayout} label="服务费承担方">
              {form.getFieldDecorator('serviceRole', {
                rules: [{ required: true, message: '请选择服务费承担方！' }],
                initialValue: formVals.serviceRole || 1,
              })(
                <Select placeholder="请选择服务费承担方" style={{ width: '100%' }}>
                  <Option value={1}>借款人</Option>
                  <Option value={2}>投资人</Option>
                </Select>,
              )}
            </FormItem>
          </Col>
        </Row>,
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>

          <Col md={12} sm={24}>
            <FormItem key="totalDays" {...this.formLayout} label="融资天数">
              {form.getFieldDecorator('totalDays', {
                rules: [{ required: true, message: '请输入融资天数！' }],
                initialValue: formVals.totalDays,
              })(<Input type={'Number'} placeholder="请输入融资天数"/>)}
            </FormItem>
          </Col>
          <Col md={12} sm={24}>
            <FormItem key="type" {...this.formLayout} label="标的类型">
              {form.getFieldDecorator('type', {
                rules: [{ required: true, message: '请选择类型！' }],
                initialValue: formVals.type,
              })(
                <Select placeholder="请选择类型" style={{ width: '100%' }}>
                  <Option value={1}>hot</Option>
                  <Option value={2}>新手</Option>
                  <Option value={3}>正常</Option>
                </Select>,
              )}
            </FormItem>
          </Col>
        </Row>,
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={12} sm={24}>
            <FormItem key="rate" {...this.formLayout} label="上标利率">
              {form.getFieldDecorator('rate', {
                rules: [{ required: true, message: '请输入上标利率！' }],
                initialValue: rate === 0 ? formVals.rate : rate,
              })(
                <Input disabled={true} placeholder="请输入上标利率"/>,
              )}
            </FormItem>
          </Col>
          <Col md={12} sm={24}>
            <FormItem key="serviceRate" {...this.formLayout} label="服务费率(%)">
              {form.getFieldDecorator('serviceRate', {
                rules: [{ required: true, message: '请输入服务费率！' }],
                initialValue: formVals.serviceRate,
              })(<Input type={'Number'} placeholder="请输入服务费率"/>)}
            </FormItem>
          </Col>
          <Col md={12} sm={24}>
            <FormItem key="type" {...this.sortformLayout} label="居间服务费类型">
              {form.getFieldDecorator('otherServiceType', {
                rules: [{ required: true, message: '请选择居间服务费类型！' }],
                initialValue: formVals.otherServiceType,
              })(
                <Select placeholder="请选择居间服务费类型" style={{ width: '100%' }}>
                  <Option value={1}>起息日前</Option>
                  <Option value={2}>还款日</Option>
                  <Option value={3}>到期日时</Option>
                </Select>,
              )}
            </FormItem>
          </Col>
          <Col md={12} sm={24}>
            <FormItem key="otherServiceRate" {...this.sortformLayout} label="居间服务费率(%)">
              {form.getFieldDecorator('otherServiceRate', {
                rules: [{ required: true, message: '请输入居间服务费率！' }],
                initialValue: formVals.otherServiceRate,
              })(<Input type={'Number'} placeholder="请输入居间服务费率"/>)}
            </FormItem>
          </Col>
        </Row>,


        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          {/*<Col md={12} sm={24}>*/}
          {/*<FormItem key="overdueServiceRate" {...this.formLayout} label="逾期服务费率">*/}
          {/*{form.getFieldDecorator('overdueServiceRate', {*/}
          {/*rules: [{ required: true, message: '请输入逾期服务费率！' }],*/}
          {/*initialValue: rate,*/}
          {/*})(<Input disabled={true} type={'Number'} placeholder="请输入逾期服务费率"/>)}*/}
          {/*</FormItem>*/}
          {/*</Col>*/}


        </Row>,
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>

        </Row>,


      ];
    }
    return [
      <Row gutter={{ md: 8, lg: 24, xl: 48 }}>

        <Col md={12} sm={24}>

          <FormItem key="channel" {...this.formLayout} label="渠道名称">
            {form.getFieldDecorator('channel', {
              rules: [{ required: true, message: '请选择资金渠道！' }],
              initialValue: formVals.channel,
            })(
              <Select placeholder="请选择资金渠道" style={{ width: '100%' }}>
                {channel.map(item => (
                  <Option value={item.key} key={item.key} disabled={item.disabled}>{item.value}</Option>
                ))}
              </Select>,
            )}
          </FormItem>
        </Col></Row>,
    ];
  };

  renderFooter = currentStep => {
    const { handleModalVisible } = this.props;

    if (currentStep === 1) {
      return [
        <Button key="back" style={{ float: 'left' }} onClick={this.backward}>
          上一步
        </Button>,
        <Button key="cancel" onClick={() => handleModalVisible()}>
          取消
        </Button>,
        <Button key="submit" type="primary" onClick={() => this.handleNext(currentStep)}>
          完成
        </Button>,
      ];
    }
    return [
      <Button key="cancel" onClick={() => handleModalVisible()}>
        取消
      </Button>,
      <Button key="forward" type="primary" onClick={() => this.handleNext(currentStep)}>
        下一步
      </Button>,
    ];
  };

  render() {
    const { modalVisible, handleModalVisible, equityModels: { companyList } } = this.props;
    const { currentStep, formVals } = this.state;
    return (
      <Modal
        width={740}
        bodyStyle={{ padding: '32px 40px 48px' }}
        destroyOnClose
        title="申请融资"
        visible={modalVisible}
        footer={this.renderFooter(currentStep)}
        onCancel={() => handleModalVisible()}
      >
        <Steps style={{ marginBottom: 28 }} size="small" current={currentStep}>
          <Step title="资金渠道选择"/>
          <Step title="基本信息录入"/>
        </Steps>
        {this.renderContent(currentStep, formVals)}
      </Modal>
    );
  }
}


export default UpdateForm;
